<template>
  <!-- 中标（选）结果公示协同审批单 -->
  <div class="tenderRegisterDetails">
    <CommonTitle titleName="中标（选）结果审批单">
      <template #rightCnBox>
        <el-button style="margin-left: auto" v-if="pageType === 'view'" @click="toPath"
          class="button_edit">查看审批流程</el-button>
      </template>
    </CommonTitle>
    <div class="contenForm">
      <el-form ref="formInlineRef" :inline="true" :model="state" class="demo-form-inline"
        :hide-required-asterisk="pageType === 'view'" :rules="rules" label-width="180">
        <el-row class="row-bg" justify="space-between">
          <el-col :span="8" v-if="pageType === 'view'">
            <el-form-item label="审批单编号:">
              <el-input disabled v-model="state.businessId" placeholder="" />
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="pageType === 'view'">
            <el-form-item label="审批状态:">
              <el-select disabled v-model="state.auditStatus" placeholder="">
                <el-option label="" value="-" />
                <el-option v-for="v in auditStatusOptions" :key="v.value" :label="v.label" :value="v.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="pageType === 'view'"> </el-col>
          <el-col :span="8">
            <el-form-item label="关联项目:">
              <el-input v-model="state.projectMainName" placeholder="" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="关联招标项目:">
              <el-input v-model="state.projectTaskName" placeholder="" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="招标项目类别:">
              <el-select v-model="state.projectTypeExplain" placeholder="" disabled>
                <!-- <el-option label="" value="-" /> -->
                <el-option v-for="v in state.tenderType" :key="v.projectTypeId" :label="v.typeName"
                  :value="v.projectTypeId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="招标方式:">
              <el-select v-model="state.tenderTypeExplain" placeholder="" disabled>
                <el-option v-for="v in selectionTypeOptions" :label="v.label" :value="v.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="相关业务部门:">
              <el-input v-model="state.responsibleDeptName" placeholder="" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="相关业务人员:">
              <el-input v-model="state.responsibleUserName" placeholder="" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="本次招标结果:" prop="tenderStatus">
              <el-select v-model="state.tenderStatus" :disabled="pageType == 'view'" @change="tenderStatusChange"
                placeholder="">
                <el-option label="中标/中选/成交" :value="1" />
                <el-option label="流标" :value="-1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="控制价:" :prop="state.tenderStatus == -1 ? '' : 'controlAmount'">
              <el-input :disabled="pageType == 'view'" v-model.number="state.controlAmount" placeholder="" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="中标/中选/成交价:" :prop="state.tenderStatus == -1 ? '' : 'tradeAmount'">
              <el-input :disabled="pageType == 'view'" v-model.number="state.tradeAmount" placeholder="" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="中标/中选/成交日期:" :prop="state.tenderStatus == -1 ? '' : 'tradeDate'">
              <!-- <el-input v-model="state.tradeDate" placeholder="" /> -->
              <el-date-picker :disabled="pageType === 'view'" v-model="state.tradeDate" type="date" size="large"
                format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="中标/中选/成交单位名称:" :prop="state.tenderStatus == -1 ? '' : 'tradeCompanyName'">
              <el-input v-model="state.tradeCompanyName" :disabled="pageType == 'view'" placeholder="" />

              <!-- <el-select
								v-model="state.tradeCompanyName"
								placeholder=""
							>
								<el-option label="" value="-" />
							</el-select> -->
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="编码:" :prop="state.tenderStatus == -1 ? '' : 'code'">
              <el-input :disabled="pageType == 'view'" v-model="state.code" placeholder="" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最高限价:" prop="ceilingPrice">
              <el-input :disabled="pageType == 'view'" v-model="state.ceilingPrice" placeholder="请输入最高限价"
                @input="state.ceilingPrice = limitInputNum(state.ceilingPrice, 9, 2, true)" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="控制价/最高限价说明:" prop="controlAmountIllustrate">
              <el-input :disabled="pageType == 'view'" v-model="state.controlAmountIllustrate" placeholder="请输入控制价/最高限价说明"
                type="textarea" :rows="4" maxlength="1000" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="中标/中选/成交价说明:" prop="tradeAmountIllustrate">
              <el-input :disabled="pageType == 'view'" v-model="state.tradeAmountIllustrate" placeholder="请输入中标/中选/成交价说明"
                type="textarea" :rows="4" maxlength="1000" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注:">
              <el-input type="textarea" :rows="4" v-model="state.remark" :disabled="pageType == 'view'" placeholder="" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

		<el-button
			class="approval-button button_funtion"
			@click="saveApplyResult"
			:loading="BtnLoading"
			v-if="pageType == 'edit'"
			>发起审批</el-button
		>
		<!-- 相关附件 -->
		<div class="card_box m-t40">
			<attachment-details
				:pageType="pageType"
				:tenderTaskId="tenderTaskId"
				:businessId="state.businessId"
				:businessType="12"
				:file-list="state.files"
				@onSuccess="onSuccess"
			></attachment-details>
		</div>

    <div class="title_ m-t40 m-b20">其他信息</div>
    <div class="other m-r20 d-flex">
      <div class="other_item d-flex">
        <div class="lebel">申请人</div>
        <div class="conetnt m-l10">{{ state.applyUserName }}</div>
      </div>
      <div class="other_item d-flex">
        <div class="lebel">申请部门</div>
        <div class="conetnt m-l10">
          {{ state.applyUserDeptName }}
        </div>
      </div>
      <div class="other_item d-flex">
        <div class="lebel">创建时间</div>
        <div class="conetnt m-l10">{{ state.createTime }}</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import CommonTitle from "@/components/CommonTitle.vue";
import { useRouter, useRoute } from "vue-router";

import {
  ElForm,
  ElCol,
  ElRow,
  ElUpload,
  ElDatePicker,
  ElSelect,
  ElMessage,
  ElMessageBox,
} from "element-plus";
import {ref, reactive, onMounted, watch, nextTick} from "vue";
import { useStore } from "vuex";
import AttachmentDetails from "./components/AttachmentDetails.vue";
import { approveApi, processApi } from "@/api/biddingProject";
import {
  selectionTypeOptions,
  auditStatusOptions,
} from "@/common/dict/dictCollect";
const store = useStore();
const router = useRouter();
const route = useRoute();
import { getURLhandler } from "@/views/constructionProjectManage/static/utools.js";
import { limitInputNum } from "@/common/utils/GlobalUtils.js"
import {useSetFormData} from "@/hooks/setFormData";

const tenderTaskId = getURLhandler(route.path).tenderTaskId;
const pageType = ref(getURLhandler(route.path).pageType);
const businessId = getURLhandler(route.path).businessId;
const state = reactive({
  tenderType: store.state.common.tenderType,
});

const {
    setData,
    getData,
    getAttributeNum,
    filterEmptyAttributes,
} = useSetFormData({
    key:`tenderRegisterDetails-${getURLhandler(route.path).tenderTaskId}-pageType${getURLhandler(route.path).pageType}`,
});

const BtnLoading = ref(false);
const rules = {
  tenderStatus: [
    {
      required: true,
      message: "请选择本次招标结果",
      trigger: "change",
    },
  ],
  /*	controlAmount: [
      {
        required: true,
        message: "请输入控制价",
        trigger: "change",
      },
    ],*/
  /*	tradeAmount: [
      {
        required: true,
        message: "请输入本次招中标/中选/成交价",
        trigger: "change",
      },
    ],*/
  code: [
    {
      required: true,
      message: "请输入编码",
      trigger: "blur",
    },
  ],
  tradeDate: [
    {
      required: true,
      message: "请选择中标/中选/成交日期",
      trigger: "change",
    },
  ],
  // tradeCompanyName: [
  // 	{
  // 		required: true,
  // 		message: "请输入中标/中选/成交单位名称",
  // 		trigger: "change",
  // 	},
  // ],
  controlAmountIllustrate: [
    { required: true, message: "请输入控制价/最高限价说明", trigger: "blur", }
  ],
  tradeAmountIllustrate: [
    { required: true, message: "请输入中标/中选/成交价说明", trigger: "blur", }
  ],
};

const onSuccess = (arr) => {
  state.files = arr;
}

const formInlineRef = ref(null);
const saveApplyResult = () => {
	if(!state.files.length){
		return ElMessage.warning('请上传附件!');
	}
	formInlineRef.value.validate((valid) => {
		if (valid) {
			ElMessageBox.confirm("是否确认发起审批?", "提示", {
				confirmButtonText: "确认发送",
				cancelButtonText: "取消",
				type: "warning",
				confirmButtonClass: "ExitConfirmButton",
				cancelButtonClass: "ExitCancelButton",
				center: true,
			}).then(() => {
				BtnLoading.value = true;
				approveApi
					.saveApplyResult({
						...state,
					})
					.then((res) => {
						if (res.code === '200') {
							ElMessage.success("操作成功");
							pageType.value = "view";
							getApplyResultInfo();
						}
						BtnLoading.value = false;
					});
			});
		}
	});
};

const isBool = ref(false);
watch([()=>pageType,()=>state],(newVal)=>{
    if(newVal[0].value==='edit' &&  Object.keys(newVal[1]).length > 2 && isBool.value){
        setData(state);
    }
},{deep:true})

const getApplyResultInfo = () => {
  approveApi.getApplyResultInfo({ tenderTaskId, businessId }).then(async (res) => {
      if (res.code === '200') {
          let data = res.data || {};

          if (getURLhandler(route.path).pageType === 'edit') {
              if (getAttributeNum(await getData()) > getAttributeNum(data)) { // 缓存中的数据比接口数据的多
                  data = Object.assign({},await getData(), filterEmptyAttributes(data))
              }
              if (getAttributeNum(await getData()) <= getAttributeNum(data)) { // 缓存中的数据比接口数据的少或者相同
                  data = filterEmptyAttributes(data)
              }
          }


          for (let key in data) {
              if (data[key]) {
                  state[key] = data[key];
              }
          }

          await nextTick(() => {
              isBool.value = true;
          })
      }
  });
};
const tenderStatusChange = (e) => {
  // console.log("---e", );
  if (e == 2) {
    formInlineRef.value.clearValidate();
  }
};
const getTypeList = () => {
  if (store.state.common.tenderType.length === 0) {
    processApi.getTypeList().then((res) => {
      if (res.code == 200) {
        state.tenderType = res.data;
        store.commit("set_tenderType", res.data);
      }
    });
  } else {
    state.tenderType = store.state.common.tenderType;
  }
};
const toPath = () => {
  window.open(state.oaLink);
};
onMounted(() => {
  getApplyResultInfo();
  getTypeList();
});
</script>
<style lang="scss" scoped>
.tenderRegisterDetails {
  .contenForm {
    width: 100%;
    border-radius: 10px;
    border: 1px solid #e3e7f1;
    padding: 32px 72px 32px 0;

    .el-form-item,
    .el-select {
      width: 100%;
    }

    .el-col {
      margin-bottom: 15px;
    }
  }

  .card_box {
    border-radius: 10px;
    border: 1px solid #e3e7f1;
    padding: 20px 35px 40px 35px;

    .title {
      span {
        color: #f12527;
      }

      height: 16px;
      font-size: 16px;
      font-weight: bold;
      color: #1a1a1a;
      line-height: 40px;
    }

    .el-button {
      border: 1px solid #fc7018;
      border-radius: 20px;
      color: #fc7018;
      width: 114px;
      height: 40px;
    }

    .card_content {
      padding: 0 69px;

      .file-content-item {
        .button-download {
          width: 77px;
          height: 32px;
          background: linear-gradient(180deg, #ffd091 0%, #ffa557 100%);
          border-radius: 4px;
          cursor: pointer;

          .icon {
            width: 18px;
            height: 18px;
          }

          span {
            color: #ffffff;
          }
        }

        .delete-icon {
          width: 20px;
          height: 20px;
          cursor: pointer;
        }
      }
    }
  }

  .other {
    border-radius: 10px;
    border: 1px solid #e3e7f1;
    padding: 32px 72px;
    justify-content: space-between;

    .other_item {
      .lebel {
        font-size: 16px;
        font-weight: 700;
        color: #1a1a1a;
        line-height: 40px;
      }

      .conetnt {
        width: 300px;
        height: 40px;
        background: #f7f7fa;
        border-radius: 4px;
        line-height: 40px;
        padding-left: 20px;
      }
    }
  }

  .title_ {
    font-size: 16px;
    font-weight: bold;
    color: #1a1a1a;
  }

  .approval-button {
    position: fixed;
    top: 80%;
    right: 120px;
    box-shadow: 0px 0px 12px 0 rgba(0, 0, 0, 0.12);
  }
}

:deep(.el-form-item__label, .fz_) {
  font-size: 12px !important;
}

:deep(.el-date-editor) {
  width: 100% !important;
}

:deep(.el-input__wrapper) {
  width: 100% !important;
}
</style>
<style>
.ExitConfirmButton {
  background: #ff6f29 !important;
  color: #fff !important;
  border: 0;
}

.ExitCancelButton {
  background-color: #fff !important;
}
</style>
